<template>
    <div class="box">
      <header class="header">
        <van-nav-bar
          title="购物车"
          left-arrow
          @click-left="$router.back()"
         />
      </header>
      <div class="content">
        <van-empty
        v-if="nodata"
        class="custom-image"
        image="https://img.yzcdn.cn/vant/custom-empty-image.png"
        description="购物车空空如也">
          <!-- <van-button round type="danger" class="bottom-button" @click="$router.push('/kind')"> -->
          <van-button round type="danger" class="bottom-button" to="/kind">
              去购物
          </van-button>
        </van-empty>
        <van-swipe-cell v-else
        v-for="(item, index) of cartlist" :key="item.cartid">
          <van-card
            :price="item.price"
            class="goods-card">
            <template #title>
              <router-link :to="{ name: 'detail', params: {proid: item.proid}}">
                <p class="van-multi-ellipsis--l2">{{item.proname}}</p>
              </router-link>
            </template>
            <template #thumb>
              <div>
                <van-checkbox v-model="item.flag" @click="selectItem(item)"></van-checkbox>
                <van-image :src="item.proimg" @click="toDetail(item.proid)" />
              </div>
            </template>
            <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" disable-input @change="updateItemNum(item.cartid,item.num)"/>
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="deleteCart(item.cartid, index)"/>
          </template>
        </van-swipe-cell>
        <van-submit-bar v-if="!nodata" :disabled="totalNum === 0" :price="totalPrice" :button-text="'提交订单('+ totalNum +')'" @submit="onSubmit">
          <van-checkbox v-model="checked" @click="selectAll(checked)">全选</van-checkbox>
        </van-submit-bar>
      </div>
    </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Empty, Button, SwipeCell, Card, SubmitBar, Checkbox, Stepper, Dialog, Toast, Image as VanImage } from 'vant'
import { getCartList, deleteCart, updateNum, updateAllFlag, updateFlag, confirmOrder } from '@/api'
import { mapState } from 'vuex'
Vue.use(NavBar)
Vue.use(Empty)
Vue.use(Button)
Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(Stepper)
Vue.use(Dialog)
Vue.use(VanImage)
Vue.use(Checkbox)
export default {
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.loginState) {
        next()
      } else {
        next('/login')
      }
    })
  },
  data () {
    return {
      nodata: false,
      checked: false
    }
  },
  computed: {
    ...mapState({
      loginState: ({ user: { loginState } }) => loginState,
      userid: ({ user: { userid } }) => userid,
      cartlist: ({ cart: { cartlist } }) => cartlist
    }),
    totalNum () {
      return this.cartlist ? this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.num : sum + 0
      }, 0) : 0
    },
    totalPrice () {
      return this.cartlist ? this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.num * item.price : sum + 0
      }, 0) * 100 : 0
    }
  },
  methods: {
    onSubmit () {
      confirmOrder({
        userid: this.userid
      }).then(res => {
        // this.$router.push('/order/' + res.data.time)
        // this.$router.push({ path: '/order/' + res.data.time })
        this.$router.push({ name: 'order', params: { time: res.data.time } })
      })
    },
    selectItem (item) {
      updateFlag({
        cartid: item.cartid,
        flag: item.flag
      }).then(() => {
        Toast('更新单选状态成功')
        if (item.flag) {
          this.checked = this.cartlist.every(item => item.flag)
        } else {
          this.checked = false
        }
      })
    },
    updateItemNum (cartid, num) {
      updateNum({
        cartid, num
      }).then(() => {
        Toast('更新数量成功')
      })
    },
    selectAll (checked) {
      updateAllFlag({
        userid: this.userid,
        checked
      }).then(() => {
        this.cartlist.forEach(item => {
          item.flag = checked
        })
        Toast('更新全选状态成功')
        // this.cartlist.map(item => {
        //  item.flag = checked
        // })
      })
    },
    deleteCart (cartid, index) {
      Dialog.confirm({
        message: '确定删除该商品吗'
      }).then(() => {
        deleteCart({ cartid }).then(res => {
          Toast('删除成功')
          this.cartlist.splice(index, 1)
          if (this.cartlist.length === 0) {
            this.nodata = true
          }
          this.checked = this.cartlist.every(item => item.flag)
        })
      }).catch(() => {})
    },
    toDetail (proid) {
      // this.$router.push('/detail/' + proid)
      // this.$router.push(`/detail/${proid}`)
      // this.$router.push({ path: '/detail/' + proid })
      this.$router.push({ name: 'detail', params: { proid } })
    }
  },
  async created () {
    const res = await getCartList({ userid: this.userid })
    if (res.data.code === '10007') {
      this.nodata = true
    } else {
      this.$store.commit('cart/change_cart_list', res.data.data)
      this.checked = this.cartlist ? this.cartlist.every(item => {
        return item.flag
      }) : false
    }
  }
}
</script>

<style lang="scss" scoped>
.delete-button {
  height: 100%;
}
.van-card__price{
  color: #f2270c;
  .van-card__price-currency{
    padding-right:0.05rem;
  }
}
.van-card__thumb {
  width: 120px;
  div {
    display: flex;
    .van-checkbox{
      width: 32px;
    }
    .van-image{
      flex: 1;
    }
  }
}
.van-card__content a{
  color: #666;
}
.header{
  height: 0.44rem !important;
}
</style>
